<?php

/**
 * Description of Taging
 * This class will generate tag input widget on active form
 * by using bootstratp taginput jquery plugin.
 * @author sadaf.siddiqui
 */
class TagInput extends CWidget
{
	/**
	 * @var CModel the data model associated with this widget.
	 */
	public $model;
	
	/**
	 * @var string the attribute associated with this widget.
	 */
	public $attribute;
	
	/**
	 * @var mixed URL or an action route that can be used to create the URL to handle search requests.
	 * */
	public $url;
	
	/**
	 * @var array the initial JavaScript options that should be passed to the jQuery Tokeninput plugin.
	 */
	public $options = array();
	
	public function init()
	{
		if (!is_array($this->options))
			$this->options = array();
	
		parent::init();
	}
	
        /**
	 * Publishes and resgisters the external javascript and css files.
	 */
	public function registerClientScripts()
	{
		$dir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets';
		$baseUrl = Yii::app()->getAssetManager()->publish($dir);
		
		$js = $baseUrl . '/bootstrap-tagsinput' . (YII_DEBUG ? '' : '.min') . '.js';
                $js2 = $baseUrl . '/bootstrap-typeahead.js' ;
		
//		$theme = isset($this->options['theme']) ? '-' . $this->options['theme'] : '';
		$css = $baseUrl . '/bootstrap-tagsinput.css'; 
		
		$cs = Yii::app()->getClientScript();
		$cs->registerScriptFile($js);
                $cs->registerScriptFile($js2);
		$cs->registerCssFile($css);
	}
        
        /**
	 * Registers the initialization script in the jQuery ready function. 
	 */
	public function registerInitScript()
	{
		$selector = '#' . CHtml::activeId($this->model, $this->attribute);
                $js1 = "url='".$this->url."'; tag=$('".$selector."');";
//                $js = <<<'EOD'
 $js = "tag.tagsinput();";
// $js = $js. "// Adding custom typeahead support using typeahead.js";
$js = $js. "tag.tagsinput('input').typeahead({\n";
 $js = $js. "source: function (query, process) {\n";
       $js = $js. " return $.get(url, { query: query }, function (data) {\n";
           $js = $js. " return process(JSON.parse(data));\n";
       $js = $js. " });\n";
   $js = $js. " }\n";
$js = $js. "}).bind('typeahead:selected', $.proxy(function (obj, datum) { \n ";
  $js = $js. "tag.tagsinput('add', datum.value);\n";
  $js = $js. "tag.tagsinput('input').typeahead('setQuery', '');\n";
$js = $js. "}, $('input')));\n";
//EOD;
			
	Yii::app()->getClientScript()->registerScript(__CLASS__.$selector, $js1.$js, CClientScript::POS_READY);
	}
        
        /* (non-PHPdoc)
     * @see CWidget::run()
     */
    public function run()
	{
		$this->registerClientScripts();
		$this->registerInitScript();
		
		echo CHtml::activeTextField($this->model, $this->attribute,array("data-role"=>"tagsinput","placeholder"=>"Add tags"));
	}

}

?>
